//
//  WJWBStatusViewModel.swift
//  WJWEIBO
//
//  Created by 文杰 许                       on 2018/9/17.
//  Copyright © 2018年 文杰 许                      . All rights reserved.
//

import Foundation

/// 上拉加载最大次数
private let maxPullupTryTimes = 3

class WJWBStatusViewModel
{
    /// 微博数组懒加载
    lazy var statusList = [WJWBModel]()
    /// 上拉加载错误次数
    private var pullupErrorTimes = 0
    
    func loadStatusData(pullUP: Bool, completion: @escaping (_ isSuccess: Bool, _ hasMoreData: Bool)->())
    {
        
        if pullUP && pullupErrorTimes > maxPullupTryTimes
        {
            completion(true, false)
            
            return
        }
        
        // 取出微博中第一条微博的id
        let since_id = pullUP ? 0 : (statusList.first?.id ?? 0)
        
        // 上拉刷新，取出微博中最后一条微博的ID
        var max_id = !pullUP ? 0 : (statusList.last?.id ?? 0)
        
        // 返回ID小于或等于max_id的微博，默认为0。
        max_id = max_id > 0 ? max_id - 1 : 0
        
        WJNetwrokManager.sharedManager.statusList(since_id: since_id, max_id: max_id) { (list, isSuccess) in
            
            // 字典转模型
            guard let arr = NSArray.yy_modelArray(with: WJWBModel.self , json: list ?? []) as? [WJWBModel] else
            {
                completion(isSuccess, false)
                return
            }
            
            // 如果是上拉加载，则直接将结果拼接到数组末尾
            if pullUP
            {
                self.statusList += arr
            }
            else // 下拉刷新，将结果插入到数组前面
            {
                self.statusList = arr + self.statusList
            }
            if pullUP && arr.count == 0
            {
                completion(isSuccess, false)
            }
            else
            {
                completion(isSuccess, true)
            }
            
        }
    }
}
